package com.xh.bussiness.jingyou.service.impl;

import java.util.ArrayList;
import java.util.List;

import com.xh.bussiness.tiku.model.Chapter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xh.bussiness.jingyou.constants.JingYouConstants;
import com.xh.bussiness.jingyou.service.IJYAuthService;
import com.xh.bussiness.jingyou.service.IJYBaseDataService;
import com.xh.bussiness.jingyou.utils.Utility;
import com.xh.bussiness.system.bean.dto.AreaDto;
import com.xh.bussiness.system.model.Area;
import com.xh.bussiness.system.model.Dictionary;
import com.xh.bussiness.tiku.model.BookChapter;
import com.xh.bussiness.tiku.model.BookVersion;
import com.xh.bussiness.tiku.model.Knowledge;
import com.xh.core.util.StringUtils;

/**
 * <p>
 * 服务类
 * </p>
 *
 * @author JQM
 * @since 2019-11-11
 */
@Service
public class JYBaseDataServiceImpl implements IJYBaseDataService {

    @Autowired
    private IJYAuthService authService;

    /**
     * 查询所有学科
     *
     * @return
     * @throws Exception
     */
    @Override
    public List<Dictionary> querySubject() throws Exception {
        String result = Utility.sendGet(authService.getToken(), JingYouConstants.URL_QUERY_SUBJECT);
        System.out.println(result);
        JSONArray array = JSON.parseArray(result);
        List<Dictionary> dicList = new ArrayList<Dictionary>();
        for (int i = 0; i < array.size(); i++) {
            JSONArray subject = array.getJSONArray(i);
//			String id = subject.getString(0);
            String code = subject.getString(1);
            String name = subject.getString(2);
            dicList.add(new Dictionary(null, "SUBJECT", code, name));
        }
        return dicList;
    }

    /**
     * 查询所有年级
     *
     * @return
     * @throws Exception
     */
    @Override
    public List<Dictionary> queryGrade() throws Exception {
        String result = Utility.sendGet(authService.getToken(), JingYouConstants.URL_QUERY_GRADE);
        JSONArray array = JSON.parseArray(result);
        List<Dictionary> dicList = new ArrayList<Dictionary>();
        for (int i = 0; i < array.size(); i++) {
            JSONObject subject = array.getJSONObject(i);
            subject.keySet().forEach(key -> {
                dicList.add(new Dictionary(null, "GRADE", key, subject.getString(key)));
            });
        }
        return dicList;
    }

    /**
     * 查询所有地区
     *
     * @return
     * @throws Exception
     */
    /*@Override
    public List<Area> queryRegion() throws Exception {
        String result = Utility.sendGet(authService.getToken(), JingYouConstants.URL_QUERY_REGION);
        JSONArray array = JSON.parseArray(result);
        List<Area> dicList = new ArrayList<Area>();
        for (int i = 0; i < array.size(); i++) {
            JSONObject region = array.getJSONObject(i);
            Area area = new Area();
            area.setName(region.getString("Name"));
            area.setParentId(region.getString("PID"));
            area.setId(region.getString("ID"));
            area.setSource(1);
            dicList.add(area);
        }
        return dicList;
    }*/

    /**
     * 根据学科查询考点
     *
     * @param subject 学科
     * @return
     * @throws Exception
     */
    @Override
    public List<Knowledge> queryKnowledge(String subject) throws Exception {
        String url = JingYouConstants.URL_ROOT_PATH + subject + "/point2";
        String result = Utility.sendGet(authService.getToken(), url);
        JSONArray array = JSON.parseArray(result);
        List<Knowledge> points = new ArrayList<Knowledge>(array.size());
        for (int i = 0; i < array.size(); i++) {
            JSONObject json = array.getJSONObject(i);
            json2Knowledge(subject, points, json, null, null, null);
        }
        return points;
    }

    /**
     * 查询所有教材
     *
     * @param subject 学科
     * @return
     * @throws Exception
     */
    @Override
    public List<BookVersion> queryBook(String subject) throws Exception {
        String url = JingYouConstants.URL_ROOT_PATH + subject + "/book2";
        String result = Utility.sendGet(authService.getToken(), url);
        JSONArray array = JSON.parseArray(result);
//		System.out.println(array.get(0));
        List<BookVersion> books = new ArrayList<BookVersion>();
        for (int i = 0; i < array.size(); i++) {
            JSONObject json = array.getJSONObject(i);
            books.add(json2Book(subject, json));
        }
        return books;
    }

    /**
     * json转Book
     *
     * @param json
     * @return
     */
    private BookVersion json2Book(String subject, JSONObject json) {
        String id = json.getString("ID");
        String name = json.getString("Name");
        String desc = json.getString("Desc");
        String versionId = json.getString("EditionID");
        String versionName = json.getString("EditionName");
        String gradeId = json.getString("GradeID");
        String gradeName = json.getString("GradeName");
        String termId = json.getString("TermID");
        String termName = json.getString("TermName");
        JSONArray arr = json.getJSONArray("Children");
        // 获取教材下的所有章节
        List<BookChapter> chapters = new ArrayList<BookChapter>();
        for (int i = 0; i < arr.size(); i++) {
            JSONObject child = arr.getJSONObject(i);
            chapters.add(json2Chapter(id, subject, child, null, chapters));
        }
        BookVersion book = new BookVersion(id, name, desc, subject,0,gradeId, gradeName, termId, termName, versionId, versionName, chapters);
        return book;
    }

    /**
     * json 转 Chapter
     *
     * @param json
     * @return
     */
    private BookChapter json2Chapter(String bookId, String subject, JSONObject json, String pId, List<BookChapter> chapters) {
        Integer index = json.getInteger("Seq");
        String id = json.getString("ID");
        String name = json.getString("Name");
        String desc = json.getString("Desc");
        BookChapter c = new BookChapter(id, name, bookId, desc, index, pId);
        JSONArray arr = json.getJSONArray("Children");
        JSONArray points = json.getJSONArray("Points");

        if (points != null) {
            List<Knowledge> knowledgeList = new ArrayList<>();
            for (int i = 0; i < points.size(); i++) {
                JSONObject child = points.getJSONObject(i);
                knowledgeList.add(json2KnowledgeByChapter(subject, child));
            }
            c.setKnowledgeList(knowledgeList);
        }
        // 递归生成树状结构
        if (arr != null) {
//			List<BookChapter> chapters = new ArrayList<BookChapter>();
            for (int i = 0; i < arr.size(); i++) {
                JSONObject child = arr.getJSONObject(i);
                chapters.add(json2Chapter(bookId, subject, child, id, chapters));
            }
//			c.setChild(chapters);
        }
        return c;
    }

    private Knowledge json2KnowledgeByChapter(String subject, JSONObject json) {
        String no = json.getString("No");
        String name = json.getString("Name");
        Knowledge k = new Knowledge();
        k.setSubject(subject);
        k.setNo(no);
        k.setName(name);
        return k;
    }

    /**
     * json 转 ExamPoint
     *
     * @param subject
     * @param json
     * @return
     */
    private void json2Knowledge(String subject, List<Knowledge> all, JSONObject json, String parentId, String parentPath, String parentPathName) {
        String no = json.getString("No");
        String name = json.getString("Name");
        String desc = json.getString("Desc");
        String id = subject;
        if (StringUtils.isEmpty(parentId)) {
            id += "~" + no;
        } else {
            id = parentId + "~" + no;
        }
        System.out.println(id);
        Knowledge k = new Knowledge();
        k.setId(id);
        k.setNo(no);
        k.setName(name);
        k.setSubject(subject);
        k.setParentId(parentId);
        k.setParentPath(parentPath + "-");
        k.setParentPathName(parentPathName + "-");
        all.add(k);
        JSONArray arr = json.getJSONArray("Children");
        // 递归生成树状结构
        if (arr != null && !arr.isEmpty()) {
            parentPath = parentPath == null ? "" : parentPath;
            parentPath += "-" + k.getId();
            parentPathName = parentPathName == null ? "" : parentPathName;
            parentPathName += "-" + k.getName();
            for (int i = 0; i < arr.size(); i++) {
                JSONObject child = arr.getJSONObject(i);
                json2Knowledge(subject, all, child, k.getId(), parentPath, parentPathName);
            }
        }
    }
}
